package com.xy.bizportdemo.messagelist;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Handler;
import android.util.Log;
import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;

import com.xy.bizportdemo.database.entity.MessageItem;
import com.xy.bizportdemo.util.BizportContentUtil;

/**
 * 企业信息详细列表的Adapter
 * Created by XIAOYUAN on 2016/11/24.
 */
public class MessageListAdapter extends CursorAdapter {
    private static final String TAG = "MessageListAdapter";

    private final LayoutInflater mFactory;
    private int mResId = -1;
    private final int MAX_CACHE_ITEMS = 100;
    private final LruCache<Long, MessageItem> mItemCache = new LruCache<Long, MessageItem>(MAX_CACHE_ITEMS);
    private boolean mIsRich;
    private Handler mHandler = null;

    public MessageListAdapter(Context context, Cursor cursor, int resId, Handler handler) {
        super(context, cursor, true);
        mResId = resId;
        mFactory = LayoutInflater.from(context);
        SharedPreferences sharedPreferences = context.getSharedPreferences(BizportContentUtil.SETTING_FILE_NAME,
                Context.CONTEXT_IGNORE_SECURITY);
        mIsRich = sharedPreferences.getBoolean(BizportContentUtil.RICHBUBBLE_MODE, true);
        mHandler = handler;
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        Log.i(TAG, "newView: pos=" + cursor.getPosition());
        View view = mFactory.inflate(mResId, parent, false);
        MessageItemViewHolder holder = new MessageItemViewHolder(context, view, mIsRich, mHandler);
        view.setTag(holder);
        return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        Log.i(TAG, "bindView: pos=" + cursor.getPosition());
        MessageItemViewHolder holder = (MessageItemViewHolder) view.getTag();
        holder.bind(getMessageListItem(cursor), cursor.getPosition());
    }

    public MessageItem getItem(int position) {
        Cursor cursor = (Cursor) super.getItem(position);
        return getMessageListItem(cursor);
    }

    private MessageItem getMessageListItem(Cursor cursor) {
        long key = getIdFromCursor(cursor);
        MessageItem item = mItemCache.get(key);
        if (item != null) {
            return item;
        }

        item = new MessageItem(cursor);
        mItemCache.put(key, item);
        return item;
    }

    private long getIdFromCursor(Cursor cursor) {
        // _id in database can be assumed to be unique
        return Long.parseLong(cursor.getString(cursor.getColumnIndex("_id")));
    }
}
